# -*- coding:utf-8 -*-

import platform,subprocess,time,threading,hashlib
import redis
import logging
import itsdangerous
from flask import Flask,jsonify,abort,make_response,url_for,request,g,render_template
from flask_restful import Api,Resource
from flask_httpauth import HTTPBasicAuth,HTTPTokenAuth


app = Flask(__name__)
api = Api(app)
auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth(scheme='Bearer')
app.config['SECRET_KEY'] = 'admin'
serializer = itsdangerous.TimedJSONWebSignatureSerializer(app.config['SECRET_KEY'], expires_in=1800)
mythreadLock = threading.Lock()

users = [
    {'username': 'admin', 'password': 'admin123'},
]


pool = redis.ConnectionPool(host='10.68.60.112', port=26379,db=0,socket_connect_timeout=30,password='admin',encoding='utf-8',decode_responses=True)
my_redis = redis.Redis(connection_pool=pool)


@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Api Message Not found'}), 404)

@auth.get_password
def get_password(username):
    for user in users:
        if user['username'] == username:
            return user['password']
    return None

@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 401)

@token_auth.verify_token
def verify_token(token):
    g.user = None
    try:
        data = serializer.loads(token)
    except:
        return False
    if 'username' in data:
        g.user = data['username']
        return True
    return False



@app.route('/')
def hello_world():
    return render_template('api.html')


@app.route('/api/token')
@auth.login_required
def get_auth_token():
    auth = request.authorization
    token = serializer.dumps({'username': 'auth.username'})
    return jsonify({ 'token': token.decode('ascii') })

    
class osAPI(Resource):
    decorators = [token_auth.login_required]
    def __init__(self):
        self.cmd1=r"F:\apache-ant-1.10.5-bin\apache-ant-1.10.5\bin\ant -f F:\apache-jmeter-2.13\apache-jmeter-2.13\demo\jmeter-as\test\build.xml"
        
    def get(self):
        osinfo=platform.platform()
        return jsonify({'osinfo': osinfo})
    
    def post(self):
        debuga1="%s begin" % threading.currentThread()
        app.logger.debug(debuga1)
        __mylocallock = mythreadLock.acquire(timeout=3)
        if __mylocallock:
            myhash=hashlib.md5()
            myhash.update(self.cmd1.encode("utf-8"))
            try:
                Jm1=my_redis.get(myhash.hexdigest())
                if not Jm1:            
                    Jm1=my_redis.set(myhash.hexdigest(),'1',ex=600)
        ##test cmd     
                    time.sleep(10)       
                    p = subprocess.Popen(self.cmd1, shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True) 
                    p.wait()
                    result_lines = p.stdout.readlines()
                    error_lines = p.stderr.readlines()                    
                    my_redis.delete(myhash.hexdigest())
                    if error_lines:
                        app.logger.error(error_lines)
                        return error_lines
                    else:
                        app.logger.info(result_lines)                 
                        return result_lines
                else:
                    redis_have1="redis have exists"
                    app.logger.error('Exception: %s' % "")
                    abort(403)
            except Exception as err:
                app.logger.error('Exception: %s' % err)
                abort(403)
            finally:
                mythreadLock.release()       
        else:
            debuga1="%s can not begin,may be lcok" % threading.currentThread()
            app.logger.debug(debuga1)
            abort(403)

api.add_resource(osAPI, '/os/api/v1.0/tasks', endpoint = 'Info')

if __name__ == '__main__':           
    app.run(host='0.0.0.0',debug=True)